package com.study.newjava8.lambda;

import com.study.newjava8.pojo.Employee;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * Stream的中间操作
 */
public class TestStreamAPI3 {

    List<Employee> employees = Arrays.asList(
            new Employee("huangsm", 22, 40020.0),
            new Employee("huangsm1", 24, 52300.0),
            new Employee("huangsm1", 24, 52300.0),
            new Employee("huangsm1", 24, 52300.0),
            new Employee("huangsm2", 26, 40100.0),
            new Employee("huangsm3", 21, 42300.0)
    );

    /**
     * 映射
     * map--接收Lambda，将元素转换成其他形式或提取信息。接收一个函数作为参数，该元素会被应用到每个元素上，并将映射成一个新的元素
     */
    @Test
    public  void test1(){
        employees.stream()
                .map(Employee::getAge)
                .distinct()
                .forEach(System.out::println);
    }

    /**
     * 将字符串转换为字符流
     * @param str
     * @return
     */
    public static Stream<Character> filterCharacter(String str){
        List<Character>list=new ArrayList<>();
        for (Character character : str.toCharArray()) {
            list.add(character);
        }
        return list.stream();
    }
    /**
     * 排序
     * sorted()--自然排序
     * sorted(Comparator com)--定制排序
     */
    @Test
    public void test3(){
        List<String> list = Arrays.asList("cc","dd","aa", "bb", "ee");
        list.stream()
                .sorted()
                .forEach(System.out::println);

        employees.stream()
                .sorted((e1,e2)->{
                    if (e1.getAge().equals(e2.getAge())){
                        return e1.getName().compareTo(e2.getName());
                    }else {
                        return e1.getAge().compareTo(e2.getAge());
                    }
                }).forEach(System.out::println);
    }


    /**
     * flatMap--接收一个函数作为参数，将流中的每个值都换成另一个流，然后把所有流连接成一个流
     */
    @Test
    public void test2(){
        List<String> list = Arrays.asList("aa", "bb", "cc");
        Stream<Stream<Character>> streamStream = list.stream()
                .map(TestStreamAPI3::filterCharacter);//{a,a},{b,b}
        //遍历
        streamStream.forEach((sm)->{
            sm.forEach(System.out::println);
        });
        //使用flatMap
        list.stream()
                .flatMap(TestStreamAPI3::filterCharacter)//{a,a,b,b}
                .forEach(System.out::println);
    }


}

